package com.beauty.controller;

import com.beauty.dto.BeautyResponse;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("api/image")
public class ImageController {

    ImageController(Environment env) {
        this.env = env;
    }

    private final Environment env;
    Configuration cfg = new Configuration(Region.region2());
    UploadManager uploadManager = new UploadManager(cfg);

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/uploadImage")
    public BeautyResponse<String> uploadImage(@RequestParam("file") MultipartFile file) throws IOException {
        var res = new BeautyResponse<String>();
        try {
            // 上传图片，不用管
            var accessKey = this.env.getProperty("accessKey");
            var bucket = this.env.getProperty("bucket");
            var secretKey = this.env.getProperty("secretKey");
            var url = this.env.getProperty("bucket_url");
            var auth = Auth.create(accessKey, secretKey);
            var fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename().split("\\.")[1];
            var upToken = auth.uploadToken(bucket, fileName);
            uploadManager.put(file.getInputStream(), fileName, upToken, null, file.getContentType());
            res.response = url + "/" + fileName;
            return res;
        } catch (Error e) {
            res.message = e.getMessage();
            return res;
        }
    }
}
